<template>
	<cl-dialog
		v-model="visible"
		class="tongkang-view-distribute"
		width="90%"
		:close-on-click-modal="false"
	>
		<el-card shadow="never">
			<template #header>
				<div class="card-header">
					<span>订单分账详情</span>
				</div>
			</template>
			<el-form :model="orderData" label-width="120px" size="default">
				<!-- 订单基本信息 -->
				<el-divider content-position="left">订单基本信息</el-divider>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="交易ID">
							<span>{{ orderData.transaction_id }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="订单编号">
							<span>{{ orderData.out_order_no }}</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="系统订单ID">
							<span>{{ orderData.order_id }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="分账状态">
							<span>{{ formatState(orderData.state) }}</span>
							<!-- <span>{{ orderData.state }}</span> -->
						</el-form-item>
					</el-col>
				</el-row>

				<!-- 分账信息 -->
				<el-divider content-position="left">分账详情</el-divider>
				<div v-if="distributeData.length > 0">
					<el-table :data="distributeData" style="width: 100%">
						<el-table-column prop="account" label="接收方账户" width="180" />
						<el-table-column label="分账金额" width="120">
							<template #default="scope">
								<span>{{ (scope.row.amount / 100).toFixed(2) }} 元</span>
							</template>
						</el-table-column>
						<el-table-column prop="description" label="描述" width="200" />
						<el-table-column
							prop="type"
							label="接收方类型"
							width="150"
							:formatter="formatReceiverType"
						/>
						<el-table-column
							prop="result"
							label="分账结果"
							width="120"
							:formatter="formatDistributeResult"
						/>
						<el-table-column
							prop="create_time"
							label="创建时间"
							width="180"
							:formatter="formatDateCreateTime"
						/>
						<el-table-column
							prop="finish_time"
							label="完成时间"
							width="180"
							:formatter="formatDateFinishTime"
						/>
						<el-table-column
							prop="fail_reason"
							label="失败原因"
							:formatter="formatFailReason"
						/>
						<el-table-column prop="detail_id" label="分账明细单号" width="200">
							<template #default="scope">
								<span class="detail-id" :title="scope.row.detail_id">{{
									scope.row.detail_id
								}}</span>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div v-else class="no-data">暂无分账信息</div>

				<!-- 操作按钮 -->
				<div class="form-actions">
					<el-button @click="closeDialog">关闭</el-button>
				</div>
			</el-form>
		</el-card>
	</cl-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';

const { service } = useCool();
const { t } = useI18n();
const visible = ref(false);
const emit = defineEmits(['closeDialog', 'update:modelValue']);

const props = defineProps({
	orderId: {
		type: Number,
		default: 0
	},
	modelValue: {
		type: Boolean,
		default: false
	}
});

// 订单数据
const orderData = reactive({
	transaction_id: '',
	out_order_no: '',
	order_id: '',
	state: ''
});

// 分账数据
const distributeData = ref([]);

// 格式化分账状态
function formatState(state: string) {
	const stateMap = {
		FINISHED: '分账完成',
		PROCESSING: '处理中'
	};
	return stateMap[state] || '未知';
}

// 格式化分账结果
// function formatResult(result: string) {
// 	const resultMap = {
// 		SUCCESS: '成功',
// 		FAIL: '失败',
// 		PROCESSING: '处理中'
// 	};
// 	return resultMap[result] || '未知';
// }

// 格式化日期时间 - 处理RFC3339标准格式
function formatDateCreateTime(data) {
	const timeStr = data.create_time;
	if (!timeStr) return '';
	try {
		// 移除时区偏移中的冒号以兼容旧版浏览器
		const normalizedTimeStr = timeStr.replace(/([+-]\d{2}):(\d{2})$/, '$1$2');
		const date = new Date(normalizedTimeStr);

		// 检查日期是否有效
		if (isNaN(date.getTime())) {
			console.error('无效的日期字符串:', timeStr);
			return '无效日期';
		}

		return date.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
			hour12: false
		});
	} catch (error) {
		console.error('日期格式化错误:', error, '输入:', timeStr);
		return '无效日期';
	}
}

// 格式化日期时间 - 处理RFC3339标准格式
function formatDateFinishTime(data) {
	const timeStr = data.finish_time;
	if (!timeStr) return '';
	try {
		// 移除时区偏移中的冒号以兼容旧版浏览器
		const normalizedTimeStr = timeStr.replace(/([+-]\d{2}):(\d{2})$/, '$1$2');
		const date = new Date(normalizedTimeStr);

		// 检查日期是否有效
		if (isNaN(date.getTime())) {
			console.error('无效的日期字符串:', timeStr);
			return '无效日期';
		}

		return date.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
			hour12: false
		});
	} catch (error) {
		console.error('日期格式化错误:', error, '输入:', timeStr);
		return '无效日期';
	}
}

// 格式化接收方类型
function formatReceiverType(data) {
	const typeMap = {
		MERCHANT_ID: '商户号',
		PERSONAL_OPENID: '个人openid'
	};
	return typeMap[data.type] || data.type;
}

// 格式化分账结果
function formatDistributeResult(data) {
	const resultMap = {
		PENDING: '待分账',
		SUCCESS: '分账成功',
		CLOSED: '已关闭'
	};
	return resultMap[data.result] || data.result;
}

// 格式化失败原因
function formatFailReason(data) {
	const reason = data.fail_reason;
	if (!reason) return '';
	const reasonMap = {
		ACCOUNT_ABNORMAL: '分账接收账户异常',
		NO_RELATION: '分账关系已解除',
		RECEIVER_HIGH_RISK: '高风险接收方',
		RECEIVER_REAL_NAME_NOT_VERIFIED: '接收方未实名',
		NO_AUTH: '分账权限已解除',
		RECEIVER_RECEIPT_LIMIT: '超出用户月收款限额',
		PAYER_ACCOUNT_ABNORMAL: '分出方账户异常',
		INVALID_REQUEST: '描述参数设置失败'
	};
	return reasonMap[reason] || reason;
}

// 重置数据
function resetData() {
	orderData.transaction_id = '';
	orderData.out_order_no = '';
	orderData.order_id = '';
	orderData.state = '';
	distributeData.value = [];
}

// 获取分账详情
async function getDistributeDetail() {
	resetData();
	if (!props.orderId) {
		ElMessage.error('订单ID不能为空');
		return;
	}

	try {
		// 调用API获取分账详情
		const distributeRes = await service.order.order.getShareOrderDetail({
			orderId: props.orderId
		});

		// 检查返回数据是否有效
		if (!distributeRes) {
			console.log('未获取到分账详情数据');
			return;
		}

		// 填充订单基本信息
		orderData.transaction_id = distributeRes.transaction_id || '';
		orderData.out_order_no = distributeRes.out_order_no || '';
		orderData.order_id = distributeRes.order_id || '';
		orderData.state = distributeRes.state || '';

		// 填充分账详情数据
		// 确保receivers是数组格式
		if (Array.isArray(distributeRes.receivers)) {
			distributeData.value = distributeRes.receivers.map(item => ({
				// 确保每个字段都有默认值，避免渲染错误
				account: item.account || '',
				amount: item.amount || 0,
				description: item.description || '',
				type: item.type || '',
				result: item.result || '',
				create_time: item.create_time || '',
				finish_time: item.finish_time || '',
				detail_id: item.detail_id || '',
				fail_reason: item.fail_reason || ''
			}));
		} else {
			distributeData.value = [];
		}
	} catch (error) {
		console.error('获取分账详情失败:', error);
		ElMessage.error('获取分账详情失败');
	}
}

// 关闭弹窗
function closeDialog() {
	emit('closeDialog');
}

// 监听 modelValue 变化
watch(
	() => props.modelValue,
	val => {
		visible.value = val;
		if (val && props.orderId) {
			getDistributeDetail();
		}
	}
);

// 监听 visible 变化
watch(
	() => visible.value,
	val => {
		emit('update:modelValue', val);
	}
);

// 监听 orderId 变化，重新获取分账详情
watch(
	() => props.orderId,
	newOrderId => {
		if (newOrderId && visible.value) {
			getDistributeDetail();
		}
	}
);
</script>

<style scoped>
.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.form-actions {
	margin-top: 30px;
	text-align: center;
}

.form-actions .el-button {
	margin: 0 10px;
}

.no-data {
	text-align: center;
	padding: 40px;
	color: #909399;
}

.detail-id {
	display: inline-block;
	max-width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}
</style>
